#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能服务器管理器
根据使用场景自动选择数据源：高频操作用缓存，关键操作用实时API
"""

import time
import logging
from typing import Dict, List, Optional, Callable
from enum import Enum
from .hybrid_server_manager import HybridServerManager, ServerInfo, DataSource

logger = logging.getLogger(__name__)


class OperationType(Enum):
    """操作类型"""
    TASK_ASSIGNMENT = "task_assignment"      # 任务分配（高频，可用缓存）
    LOAD_BALANCING = "load_balancing"        # 负载均衡（中频，可用缓存）
    SCALING_DECISION = "scaling_decision"    # 扩缩容决策（低频，需要实时）
    HEALTH_CHECK = "health_check"            # 健康检查（中频，可用缓存）
    STATUS_REPORT = "status_report"          # 状态报告（低频，需要实时）


class SmartServerManager:
    """智能服务器管理器"""
    
    def __init__(self, hai_client):
        self.hybrid_manager = HybridServerManager(hai_client)
        self.hai_client = hai_client
        
        # 操作策略配置
        self.operation_strategies = {
            OperationType.TASK_ASSIGNMENT: {
                "use_cache": True,
                "cache_ttl": 5,  # 5秒缓存
                "fallback_to_api": True
            },
            OperationType.LOAD_BALANCING: {
                "use_cache": True,
                "cache_ttl": 10,  # 10秒缓存
                "fallback_to_api": True
            },
            OperationType.SCALING_DECISION: {
                "use_cache": False,  # 扩缩容决策必须用实时数据
                "cache_ttl": 0,
                "fallback_to_api": False
            },
            OperationType.HEALTH_CHECK: {
                "use_cache": True,
                "cache_ttl": 15,  # 15秒缓存
                "fallback_to_api": True
            },
            OperationType.STATUS_REPORT: {
                "use_cache": False,  # 状态报告必须用实时数据
                "cache_ttl": 0,
                "fallback_to_api": False
            }
        }
    
    def get_servers(self, operation_type: OperationType = OperationType.TASK_ASSIGNMENT) -> List[ServerInfo]:
        """
        根据操作类型智能获取服务器列表
        
        Args:
            operation_type: 操作类型
            
        Returns:
            服务器列表
        """
        strategy = self.operation_strategies[operation_type]
        
        if strategy["use_cache"]:
            # 尝试使用缓存
            servers = self.hybrid_manager.get_servers(use_cache=True)
            
            # 检查缓存是否有效
            if self._is_cache_valid(servers, strategy["cache_ttl"]):
                logger.debug(f"使用缓存获取服务器列表: {operation_type.value}")
                return servers
            
            # 缓存无效，尝试从API获取
            if strategy["fallback_to_api"]:
                logger.debug(f"缓存无效，从API获取: {operation_type.value}")
                return self.hybrid_manager.get_servers(use_cache=False)
        
        # 直接使用API
        logger.debug(f"直接使用API获取: {operation_type.value}")
        return self.hybrid_manager.get_servers(use_cache=False)
    
    def get_available_servers(self, operation_type: OperationType = OperationType.TASK_ASSIGNMENT) -> List[ServerInfo]:
        """
        获取可用服务器列表
        
        Args:
            operation_type: 操作类型
            
        Returns:
            可用服务器列表
        """
        servers = self.get_servers(operation_type)
        return [s for s in servers if s.status == "RUNNING"]
    
    def select_best_server(self, preferred_regions: List[str] = None) -> Optional[ServerInfo]:
        """
        选择最佳服务器（用于任务分配）
        
        Args:
            preferred_regions: 首选地域
            
        Returns:
            最佳服务器
        """
        servers = self.get_available_servers(OperationType.TASK_ASSIGNMENT)
        
        if not servers:
            return None
        
        # 过滤首选地域
        if preferred_regions:
            servers = [s for s in servers if s.region in preferred_regions]
        
        if not servers:
            return None
        
        # 选择负载最低的服务器
        best_server = min(servers, key=lambda s: s.current_tasks)
        return best_server
    
    def get_scaling_metrics(self) -> Dict[str, any]:
        """
        获取扩缩容指标（使用实时数据）
        
        Returns:
            扩缩容指标
        """
        servers = self.get_servers(OperationType.SCALING_DECISION)
        
        total_servers = len(servers)
        running_servers = len([s for s in servers if s.status == "RUNNING"])
        healthy_servers = len([s for s in servers if s.status == "RUNNING" and 
                              time.time() - s.last_health_check < 60])
        
        # 计算平均负载
        if running_servers > 0:
            total_tasks = sum(s.current_tasks for s in servers if s.status == "RUNNING")
            avg_load = total_tasks / running_servers
        else:
            avg_load = 0
        
        return {
            "total_servers": total_servers,
            "running_servers": running_servers,
            "healthy_servers": healthy_servers,
            "average_load": avg_load,
            "data_source": "real_time_api",
            "timestamp": time.time()
        }
    
    def get_status_report(self) -> Dict[str, any]:
        """
        获取状态报告（使用实时数据）
        
        Returns:
            状态报告
        """
        servers = self.get_servers(OperationType.STATUS_REPORT)
        
        # 按地域统计
        region_stats = {}
        for server in servers:
            if server.region not in region_stats:
                region_stats[server.region] = {
                    "total": 0,
                    "running": 0,
                    "healthy": 0
                }
            
            stats = region_stats[server.region]
            stats["total"] += 1
            if server.status == "RUNNING":
                stats["running"] += 1
                if time.time() - server.last_health_check < 60:
                    stats["healthy"] += 1
        
        return {
            "servers": {
                "total": len(servers),
                "running": len([s for s in servers if s.status == "RUNNING"]),
                "healthy": len([s for s in servers if s.status == "RUNNING" and 
                               time.time() - s.last_health_check < 60])
            },
            "regions": region_stats,
            "data_source": "real_time_api",
            "timestamp": time.time()
        }
    
    def _is_cache_valid(self, servers: List[ServerInfo], cache_ttl: int) -> bool:
        """
        检查缓存是否有效
        
        Args:
            servers: 服务器列表
            cache_ttl: 缓存生存时间
            
        Returns:
            缓存是否有效
        """
        if not servers:
            return False
        
        current_time = time.time()
        for server in servers:
            if current_time - server.last_sync_time > cache_ttl:
                return False
        
        return True
    
    def force_sync(self) -> Dict[str, any]:
        """
        强制同步
        
        Returns:
            同步结果
        """
        return self.hybrid_manager.force_sync()
    
    def update_server_status(self, instance_id: str, **kwargs) -> bool:
        """
        更新服务器状态
        
        Args:
            instance_id: 服务器ID
            **kwargs: 要更新的字段
            
        Returns:
            是否更新成功
        """
        return self.hybrid_manager.update_server_status(instance_id, **kwargs)
    
    def add_server(self, instance_id: str, region: str, gpu_type: str) -> bool:
        """
        添加服务器
        
        Args:
            instance_id: 服务器ID
            region: 地域
            gpu_type: GPU类型
            
        Returns:
            是否添加成功
        """
        return self.hybrid_manager.add_server(instance_id, region, gpu_type)
    
    def remove_server(self, instance_id: str) -> bool:
        """
        移除服务器
        
        Args:
            instance_id: 服务器ID
            
        Returns:
            是否移除成功
        """
        return self.hybrid_manager.remove_server(instance_id)
